﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Cryptography;

using edowork.com.SQL2005;
using edowork.com.Model;

namespace WebInvoicingsys.system.purchase
{
    public partial class purchaseplan_edit : System.Web.UI.Page
    {
        //前台输出提示信息变量
        public string alert_msg = "", Total_qty = "0", Total_in_price = "0", Total_in_money = "0";

        string id = "", years = "", months="";

        /// <summary>
        /// 取得传入的参数
        /// </summary>
        /// <returns></returns>
        private bool GetParma()
        {
            try
            {
                id = Request.Params["id"].ToString();
                years = Request.Params["years"].ToString();
                months = Request.Params["months"].ToString();
            }
            catch
            {
                //显示出错信息
                alert_msg = String.Format(Scripts.alert_warning, Errormsg.er_Parampost);
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);
                return false;
            }

            return true;
        }

        //绑定单据主信息
        private void BindInfo()
        {
            Execute exec = new Execute(Session["connectionString"].ToString());

            string sql = "", error_msg = "";

            //构造SQL语句
            sql = @"select a.pspid, a.years, a.quarter, a.month, a.userid, a.sysdate, a.remark, a.m_stu, a.m_date, a.m_id, a.userid, b.username
                      from purchaseplan a, sysuser b
                       where a.userid=b.userid
                        and  a.pspid='{0}'";


            sql = String.Format(sql, id);

            DataSet ds = exec.ExecSQLQueryDataSet(sql, ref error_msg);

            if ((ds == null) || (ds.Tables.Count <= 0) || (ds.Tables[0].Rows.Count <= 0))
            {
                alert_msg = String.Format(Scripts.alert_warning, error_msg);
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);
                return;
            }

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                txt_years.Text = dr["years"].ToString();
                txt_months.Text = dr["month"].ToString();
                txt_remark.Text = dr["remark"].ToString();
            }
        }

        //绑定Session中的货品数据
        private void Bind()
        {
            DataTable dtList = new DataTable();

            dtList.Columns.Add("dgvID");
            dtList.Columns.Add("productcode");
            dtList.Columns.Add("productname");
            dtList.Columns.Add("productshortname");
            dtList.Columns.Add("goodsclassname");
            dtList.Columns.Add("goodsunitname");
            dtList.Columns.Add("goodsspecname");
            dtList.Columns.Add("stackname");
            dtList.Columns.Add("guardname");
            dtList.Columns.Add("qty");
            dtList.Columns.Add("in_price");
            dtList.Columns.Add("in_money");

            DataTable dtData = ((purchaseplan_product_class)Session["purchaseplan_product"]).getList().Copy();

            foreach (DataRow dr in dtData.Rows)
            {
                DataRow drnew = dtList.NewRow();

                drnew["dgvID"] = (dtList.Rows.Count + 1).ToString();
                drnew["productcode"] = dr["productcode"].ToString();
                drnew["productname"] = dr["productname"].ToString();
                drnew["productshortname"] = dr["productshortname"].ToString();
                drnew["goodsclassname"] = dr["goodsclassname"].ToString();
                drnew["goodsunitname"] = dr["goodsunitname"].ToString();
                drnew["goodsspecname"] = dr["goodsspecname"].ToString();
                drnew["stackname"] = dr["stackname"].ToString();
                drnew["guardname"] = dr["guardname"].ToString();
                drnew["qty"] = dr["qty"].ToString();
                drnew["in_price"] = dr["in_price"].ToString();
                drnew["in_money"] = dr["in_money"].ToString();

                dtList.Rows.Add(drnew);
            }

            rplist.DataSource = dtList;
            rplist.DataBind();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetParma();

                try
                {
                    ((purchaseplan_product_class)Session["purchaseplan_product"]).Reset();
                }
                catch
                {
                    Session.Add("purchaseplan_product", new purchaseplan_product_class(Session["connectionString"].ToString()));
                }
                finally
                {
                    ((purchaseplan_product_class)Session["purchaseplan_product"]).getDataList(id);
                }

                BindInfo();

                Bind();

                Total_qty = ((purchaseplan_product_class)Session["purchaseplan_product"]).Total_qty.ToString();
                Total_in_price = ((purchaseplan_product_class)Session["purchaseplan_product"]).Total_in_price.ToString();
                Total_in_money = ((purchaseplan_product_class)Session["purchaseplan_product"]).Total_in_money.ToString();
            }
        }

        //保存
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (GetParma() == false)
            {
                return;
            }

            alert_msg = "";

            edowork.com.Model.purchaseplanInfo purchaseplanInfo = new purchaseplanInfo();
            edowork.com.Model.purchaseplandetailInfo purchaseplandetailInfo = new purchaseplandetailInfo();

            purchaseplanInfo.Remark = txt_remark.Text.Trim();
          
            if (((purchaseplan_product_class)Session["purchaseplan_product"]).getListTotal() <= 0)
            {
                alert_msg = String.Format(Scripts.alert_warning, "请输入采购的货品信息");

                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                return;
            }

            //保存数据入数据库
            using (edowork.com.SQL2005.TranUtil tranutil = new TranUtil(Session["connectionString"].ToString()))
            {
                System.Data.SqlClient.SqlTransaction tran = null;

                try
                {
                    tran = tranutil.GetSqlTransaction();
                }
                catch (Exception er)
                {
                    alert_msg = String.Format(Scripts.alert_warning, er.Message);

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                edowork.com.SQL2005.Execute exec = new Execute(Session["connectionString"].ToString());

                string sql = "";
                int result = -1;

                //保存入purchaseplan表
                sql = @"update purchaseplan set remark='{1}' where pspid='{0}' and m_stu='0'";

                sql = String.Format(sql, id, purchaseplanInfo.Remark);

                result = exec.ExecSQLQueryInt(sql, ref alert_msg, tran);

                if (result <= 0)
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, alert_msg);

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                //清空purchaseplandetail中的数据
                sql = String.Format("delete from purchaseplandetail where pspid='{0}'", id);

                result = exec.ExecSQLQueryInt(sql, ref alert_msg, tran);

                if (result <= 0)
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, alert_msg);

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }


                //保存入purchaseplandetail表
                DataTable dtData = ((purchaseplan_product_class)Session["purchaseplan_product"]).getList().Copy();

                foreach (DataRow dr in dtData.Rows)
                {
                    //保存入purchaseplandetail表
                    sql = String.Format(purchaseplandetailInfo.SQL_Insert(), id,
                                        dr["productcode"].ToString(), dr["qty"].ToString(), "0",
                                        dr["in_price"].ToString(), dr["in_money"].ToString());

                    result = exec.ExecSQLQueryInt(sql, ref alert_msg, tran);

                    if (result <= 0)
                    {
                        tran.Rollback();
                        tranutil.CloseConnection();

                        alert_msg = String.Format(Scripts.alert_warning, alert_msg);

                        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                        return;
                    }
                }

                tran.Commit();
                tranutil.CloseConnection();
            }

            alert_msg = String.Format(Scripts.alert_success, Errormsg.success_Save);

            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);
        }

        //返回
        protected void btnReturn_Click(object sender, EventArgs e)
        {
            GetParma();

            string url = "/system/purchase/purchaseplan_list.aspx?years={0}&months={1}";

            url = String.Format(url, years, months);

            Response.Redirect(url);
        }

        //添加货品
        protected void btAddproduct_Click(object sender, EventArgs e)
        {
            alert_msg = "";

            string productu_code = uc_from_product.getValue();
            string qty = txt_qty.Text.Trim();
            string in_price = txt_in_price.Text.Trim();
            string in_money = txt_in_money.Text.Trim();

            if (((purchaseplan_product_class)Session["purchaseplan_product"]).Add(productu_code, qty, in_price, in_money, ref alert_msg) == false)
            {
                alert_msg = String.Format(Scripts.alert_warning, alert_msg);

                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                return;
            }

            uc_from_product.clearValue();
            txt_qty.Text = "";
            txt_in_price.Text = "";
            txt_in_money.Text = "";

            Bind();

            Total_qty = ((purchaseplan_product_class)Session["purchaseplan_product"]).Total_qty.ToString();
            Total_in_price = ((purchaseplan_product_class)Session["purchaseplan_product"]).Total_in_price.ToString();
            Total_in_money = ((purchaseplan_product_class)Session["purchaseplan_product"]).Total_in_money.ToString();
        }

        //删除货品
        protected void rplist_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            string id = e.CommandArgument.ToString();

            switch (e.CommandName)
            {
                case "Delete":
                    {
                        ((purchaseplan_product_class)Session["purchaseplan_product"]).Delect(id);

                        //查询
                        Bind();

                        Total_qty = ((purchaseplan_product_class)Session["purchaseplan_product"]).Total_qty.ToString();
                        Total_in_price = ((purchaseplan_product_class)Session["purchaseplan_product"]).Total_in_price.ToString();
                        Total_in_money = ((purchaseplan_product_class)Session["purchaseplan_product"]).Total_in_money.ToString();

                        alert_msg = String.Format(Scripts.alert_success, Errormsg.success_Delete);

                        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                        break;
                    }
                default:
                    {
                        break;
                    }
            }
        }
    }
}